package com.lastproject.ejb.dao;

import java.util.ArrayList;
import java.util.List;

import javax.ejb.EJB;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

import com.lastproject.dto.DomainDTO;
import com.lastproject.ejb.entities.Domain;
import com.lastproject.ejb.util.DomainConversion;



/**
 * Session Bean implementation class DomainDAO
 * author : Dan Gandila
 */
@Stateless
public class DomainDAO implements DomainDAORemote {

	@PersistenceContext(unitName = "LastProjectEJB")
	private EntityManager em;
	@EJB DomainConversion conv;
	
    public DomainDAO() {
    }

	@Override
	public void create(DomainDTO entity) {
		em.persist(conv.fromDTO(entity));
	}

	@Override
	public void edit(DomainDTO entity) {
		em.merge(conv.fromDTO(entity));
	}

	@Override
	public void remove(DomainDTO entity) {	
		Domain u = em.find(Domain.class,entity.getId());
		em.remove(em.merge(u));
	}

	@Override
	public DomainDTO findByID(Object id) {
		Domain d = em.find(Domain.class,id);
		DomainDTO domain = conv.fromEntity(d);
		return domain;
	}

	@Override
	public List<DomainDTO> findAll() {
		List<Domain> domains = em.createNamedQuery("Domain.findAll",Domain.class).getResultList();
        List<DomainDTO> domainsDto = new ArrayList<DomainDTO>();    

        for(Domain d:domains){
                DomainDTO dDto = new DomainDTO();
                dDto = conv.fromEntity(d);
                domainsDto.add(dDto);
        }
        return domainsDto;
	}

	@Override
	public List<DomainDTO> findByName(String name) {
		List<Domain> domains = em.createQuery("SELECT d FROM Domain d WHERE d.name LIKE :name",Domain.class).setParameter("name", name).getResultList();
        List<DomainDTO> domainsDto = new ArrayList<DomainDTO>();    

        for(Domain d:domains){
                DomainDTO dDto = new DomainDTO();
                dDto = conv.fromEntity(d);
                domainsDto.add(dDto);
        }
        return domainsDto;
	}

}
